from flask import Blueprint, render_template, redirect, url_for, flash, request, abort, current_app
from flask_login import login_required
from datetime import datetime

from app import db
from app.models.blind_box import BlindBox, BoxContent, Product
from app.models.supermarket import Supermarket
from app.utils.tracking import track_user_behavior
from app.utils.auth import admin_required
from sqlalchemy.exc import SQLAlchemyError
import os
from werkzeug.utils import secure_filename
import uuid

blind_box = Blueprint('blind_box', __name__, url_prefix='/blind_box')

@blind_box.route('/list')
@login_required
def list():
    """盲盒列表"""
    # 获取筛选参数
    category = request.args.get('category')
    status = request.args.get('status')
    market_id = request.args.get('market_id')
    
    query = BlindBox.query
    
    # 应用筛选条件
    if category:
        query = query.filter(BlindBox.category == category)
    if status:
        query = query.filter(BlindBox.status == int(status))
    if market_id:
        query = query.filter(BlindBox.market_id == int(market_id))
    
    # 获取所有盲盒
    blind_boxes = query.order_by(BlindBox.update_time.desc()).all()
    
    # 获取所有超市
    supermarkets = Supermarket.query.all()
    
    # 获取所有分类
    categories = db.session.query(BlindBox.category).distinct().all()
    categories = [c[0] for c in categories if c[0]]
    
    return render_template('blind_box/list.html', 
                         blind_boxes=blind_boxes, 
                         supermarkets=supermarkets,
                         categories=categories)

@blind_box.route('/detail/<int:box_id>')
@login_required
def detail(box_id):
    """盲盒详情"""
    blind_box = BlindBox.query.get_or_404(box_id)
    
    # 记录用户查看行为
    track_user_behavior('view', box_id, 'box')
    
    return render_template('blind_box/detail.html', blind_box=blind_box)

@blind_box.route('/add', methods=['GET', 'POST'])
@login_required
def add():
    """添加盲盒"""
    supermarkets = Supermarket.query.all()
    
    if request.method == 'POST':
        name = request.form.get('name')
        market_id = request.form.get('market_id')
        description = request.form.get('description')
        original_price = request.form.get('original_price')
        discount_price = request.form.get('discount_price')
        category = request.form.get('category')
        stock = request.form.get('stock', 0)
        unique_code = request.form.get('unique_code')
        image_url = request.form.get('image_url')
        
        # 计算折扣率
        discount_rate = None
        if original_price and discount_price:
            original_price = float(original_price)
            discount_price = float(discount_price)
            if original_price > 0:
                discount_rate = round(discount_price / original_price, 2)
        
        # 创建新盲盒
        new_box = BlindBox(
            name=name,
            market_id=market_id,
            description=description,
            original_price=original_price,
            discount_price=discount_price,
            discount_rate=discount_rate,
            category=category,
            stock=stock,
            unique_code=unique_code,
            create_time=datetime.now(),
            status=1,
            image_url=image_url
        )
        
        db.session.add(new_box)
        db.session.commit()
        
        flash('盲盒添加成功!', 'success')
        return redirect(url_for('blind_box.list'))
        
    return render_template('blind_box/form.html', supermarkets=supermarkets, box=None)

@blind_box.route('/edit/<int:box_id>', methods=['GET', 'POST'])
@login_required
def edit(box_id):
    """编辑盲盒"""
    box = BlindBox.query.get_or_404(box_id)
    supermarkets = Supermarket.query.all()
    
    if request.method == 'POST':
        box.name = request.form.get('name')
        box.market_id = request.form.get('market_id')
        box.description = request.form.get('description')
        box.original_price = request.form.get('original_price')
        box.discount_price = request.form.get('discount_price')
        box.category = request.form.get('category')
        box.stock = request.form.get('stock', 0)
        box.unique_code = request.form.get('unique_code')
        box.image_url = request.form.get('image_url')
        
        # 计算折扣率
        if box.original_price and box.discount_price and float(box.original_price) > 0:
            box.discount_rate = round(float(box.discount_price) / float(box.original_price), 2)
        
        db.session.commit()
        
        flash('盲盒信息更新成功!', 'success')
        return redirect(url_for('blind_box.list'))
        
    return render_template('blind_box/form.html', supermarkets=supermarkets, box=box)

@blind_box.route('/delete/<int:box_id>')
@login_required
def delete(box_id):
    """删除盲盒"""
    box = BlindBox.query.get_or_404(box_id)
    
    db.session.delete(box)
    db.session.commit()
    
    flash('盲盒已删除!', 'success')
    return redirect(url_for('blind_box.list'))

@blind_box.route('/toggle_status/<int:box_id>')
@login_required
def toggle_status(box_id):
    """切换盲盒状态（上架/下架）"""
    box = BlindBox.query.get_or_404(box_id)
    
    # 切换状态
    box.status = 0 if box.status == 1 else 1
    db.session.commit()
    
    status_text = '上架' if box.status == 1 else '下架'
    flash(f'盲盒已{status_text}!', 'success')
    return redirect(url_for('blind_box.list'))

@blind_box.route('/contents/<int:box_id>')
@admin_required
def box_contents(box_id):
    """盲盒内容管理页面"""
    box = BlindBox.query.get_or_404(box_id)
    contents = BoxContent.query.filter_by(box_id=box_id).all()
    
    # 确保每个内容关联的产品信息也可用
    for content in contents:
        content.product = Product.query.get(content.product_id)
    
    return render_template('blind_box/content_list.html', box=box, contents=contents)

@blind_box.route('/contents/<int:box_id>/add', methods=['POST'])
@admin_required
def add_content(box_id):
    """添加盲盒内容"""
    box = BlindBox.query.get_or_404(box_id)
    
    # 获取表单数据
    product_id = request.form.get('product_id')
    quantity = request.form.get('quantity', 1, type=int)
    
    # 验证产品是否存在
    product = Product.query.get(product_id)
    if not product:
        flash('选择的商品不存在', 'danger')
        return redirect(url_for('blind_box.box_contents', box_id=box_id))
    
    # 检查是否已经存在该产品
    existing = BoxContent.query.filter_by(box_id=box_id, product_id=product_id).first()
    if existing:
        flash('该商品已在盲盒内容中，不可重复添加', 'warning')
        return redirect(url_for('blind_box.box_contents', box_id=box_id))
    
    # 创建新的盲盒内容记录
    try:
        content = BoxContent(
            box_id=box_id,
            product_id=product_id,
            quantity=quantity,
            create_time=datetime.now()
        )
        db.session.add(content)
        db.session.commit()
        flash('内容添加成功', 'success')
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"添加盲盒内容失败: {str(e)}")
        flash('内容添加失败，请重试', 'danger')
    
    return redirect(url_for('blind_box.box_contents', box_id=box_id))

@blind_box.route('/contents/<int:box_id>/delete')
@admin_required
def delete_content(box_id):
    """删除盲盒内容"""
    content_id = request.args.get('content_id', type=int)
    if not content_id:
        flash('未提供内容ID', 'danger')
        return redirect(url_for('blind_box.box_contents', box_id=box_id))
    
    content = BoxContent.query.get_or_404(content_id)
    
    # 确保内容属于指定的盲盒
    if content.box_id != box_id:
        flash('无权删除此内容', 'danger')
        return redirect(url_for('blind_box.box_contents', box_id=box_id))
    
    try:
        db.session.delete(content)
        db.session.commit()
        flash('内容已删除', 'success')
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"删除盲盒内容失败: {str(e)}")
        flash('内容删除失败，请重试', 'danger')
    
    return redirect(url_for('blind_box.box_contents', box_id=box_id)) 